import { CSSProperties, memo, useCallback, useMemo, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Link } from 'react-router-dom';
import {
  Avatar,
  Button,
  Form,
  Image,
  Input,
  InputNumber,
  message,
  Popconfirm,
  Radio,
  Switch,
  Table,
  Tag,
} from 'antd';
import { ColumnsType } from 'antd/es/table';
import {
  resAddCategoryAdmin,
  resCategoryList,
  resChangeCategoryAdmin,
  resDeleteCategoryAdmin,
  resStatusCategoryAdmin,
} from '@/services/category';
import {
  resAddSlidesAdmin,
  resChangeSlidesAdmin,
  resDeleteSlidesAdmin,
  resSeqSlidesAdmin,
  resSlides,
  resStatusSlidesAdmin,
} from '@/services/slides';
import { UploadOutlined } from '@ant-design/icons';
import { useAntdTable, useRequest } from 'ahooks';
import { isString, pick } from 'lodash';
import {
  labelCol,
  validateMessage,
  wrapperCol,
} from '@/components/AddressFormModal';
import EditModal from '@/components/EditModal';
import UploadImage from '@/components/UploadImage';
import { orderNoStyle, style } from '@/pages/Profile/components/MyOrders';
import { OpenAndOperation } from '@/pages/Profile/components/MySell';
import { formatTime, formatUrl } from '@/utils/format';

const createColumns = (
  refresh: () => void,
  showModal: (
    status: 'edit' | 'add',
    defaultValue?: API.CategoryListStruct
  ) => void
): ColumnsType<API.CategoryListStruct> => [
  {
    title: <div className={' font-bold'}>编号</div>,
    dataIndex: 'id',
    align: 'center',
    ellipsis: true,
  },
  {
    title: <div className={' font-bold'}>名称</div>,
    dataIndex: 'name',
    align: 'center',
    ellipsis: true,
  },
  {
    title: <div className={' font-bold'}>上级编号</div>,
    dataIndex: 'p_id',
    align: 'center',
    ellipsis: true,
  },
  {
    title: <div className={' font-bold'}>等级</div>,
    dataIndex: 'level',
    align: 'center',
    ellipsis: true,
  },
  {
    title: <div className={' font-bold'}>是否禁用</div>,
    dataIndex: 'status',
    align: 'center',
    ellipsis: true,
    render: (status, category) => (
      <Switch
        checked={Boolean(status)}
        onChange={() => {
          resStatusCategoryAdmin(category.id).then(() => {
            refresh();
          });
        }}
      />
    ),
  },
  {
    title: <div className={'font-bold'}>操作</div>,
    key: 'operate',
    ellipsis: true,
    render: (_, category) => [
      <Button
        type={'link'}
        key={'edit'}
        onClick={() => {
          showModal('edit', category);
        }}
      >
        编辑
      </Button>,
      <Popconfirm
        key={'delete'}
        title={'是否确定删除该分类？'}
        okText={'确定'}
        cancelText={'取消'}
        onConfirm={() => {
          resDeleteCategoryAdmin(category.id).then(() => {
            message.success('删除成功');
            refresh();
          });
        }}
      >
        <Button type={'link'}>删除</Button>
      </Popconfirm>,
    ],
  },
];

const CategoryManage: FC<PropsWithChildren<{}>> = () => {
  const { tableProps, refresh } = useAntdTable(
    () => {
      return resCategoryList({
        status: 'all',
      }).then((res) => {
        return {
          list: res,
          total: res.length,
        };
      });
    },
    { cacheKey: 'useCategoryAdminCache' }
  );

  const [editForm] = Form.useForm<API.AddCategoryParams>();

  const [isModalOpen, setIsModalOpen] = useState<OpenAndOperation>({
    show: false,
    defaultValue: {} as API.CategoryListStruct,
    status: 'add',
  });
  const showModal = useCallback(
    (status: 'edit' | 'add', defaultValue?: API.CategoryListStruct) => {
      if (status === 'edit') {
        editForm.setFieldsValue(pick(defaultValue, ['name', 'p_id']));
      } else {
        editForm.resetFields();
      }
      setIsModalOpen({ show: true, defaultValue, status });
    },
    []
  );
  const handleCancel = useCallback(
    () => setIsModalOpen({ ...isModalOpen, show: false }),
    [isModalOpen]
  );

  const onFinish = useCallback(
    (value: any) => {
      if (isModalOpen.status == 'add') {
        resAddCategoryAdmin({ ...value, p_id: parseInt(value.p_id) }).then(
          () => {
            message.success('添加分类成功');
            handleCancel();
            refresh();
          }
        );
      } else if (isModalOpen.status == 'edit') {
        if (isModalOpen.defaultValue) {
          if (!value.category_id)
            value.category_id = isModalOpen.defaultValue.category_id;
          resChangeCategoryAdmin(isModalOpen.defaultValue.id, value).then(
            () => {
              message.success('修改分类成功');
              handleCancel();
              refresh();
            }
          );
        }
      }
    },
    [isModalOpen, refresh, handleCancel]
  );

  const editModal = (
    <EditModal
      title={isModalOpen.status === 'add' ? '添加分类' : '编辑分类'}
      isModalOpen={isModalOpen.show}
      onCancel={handleCancel}
      width={500}
    >
      <Form
        validateMessages={validateMessage}
        labelCol={labelCol}
        wrapperCol={wrapperCol}
        onFinish={onFinish}
        form={editForm}
      >
        <Form.Item label="名称" name="name" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item label="上级id" name="p_id" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <div>
          <Button htmlType={'submit'} block type={'primary'}>
            提交
          </Button>
        </div>
      </Form>
    </EditModal>
  );

  const columns = createColumns(refresh, showModal);

  return (
    <div style={style} className={'p-4 hidden-scrollbar'}>
      <div className={'text-right mb-4 '}>
        <Button
          type={'primary'}
          onClick={() => {
            showModal('add');
          }}
        >
          新增
        </Button>
      </div>
      <div className={'rounded-lg overflow-hidden'}>
        <Table
          columns={columns}
          rowKey="id"
          {...tableProps}
          pagination={false}
        />
      </div>
      {editModal}
    </div>
  );
};

export default memo(CategoryManage);
